<!DOCTYPE html>
<html class="x-admin-sm">
{include file='public/header'}
<link rel="stylesheet" href="/admin/xadmin/lib/layui/css/inputTag.css">
<script type="text/javascript" src="/admin/xadmin/lib/layui/inputTag.js" charset="utf-8"></script>
<style>
    .layui-input-block {
        margin-left: 165px;
    }

    #selectAccount .layui-input-block {
        margin-left: 0;
    }

    .designated_amount_echo {
        width: 50%;
    }

    .designated_amount_echo .item {
        display: flex;
        justify-content: space-between;
        margin-top: 10px;
        height: 38px;
    }

    .designated_amount_echo .item div {
        display: flex;
        align-items: center;
    }

    .designated_amount_echo .item .content div {
        margin-right: 10px;
    }

    .designated_amount_echo .item input {
        flex: 1;
        width: 75px;
        height: 30px;
    }

    .designated_amount_echo .item .operate span {
        margin-right: 15px;
        display: inline-block;
        width: 20px;
        height: 20px;
        padding: 0;
        line-height: 20px;
    }

    .layui-form-label {
        width: 135px;
    }

    .fairy-tag {
        display: flex;
    }

    .fairy-tag-container {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
    }
</style>

<body>
    <div class="x-body" id="app">
        <form class="layui-form" lay-filter="formAjax">
            <div class="layui-form-item">
                <label class="layui-form-label">
                    短剧名称
                </label>
                <div class="layui-input-block">
                    <input type="text" id="name" disabled autocomplete="off" class="layui-input" value="" />
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    <span class="x-red">*</span>是否开启投放
                </label>
                <div class="layui-input-block">
                    <input type="radio" name="link_switch" value="1" title="开启" checked>
                    <input type="radio" name="link_switch" value="0" title="关闭">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    推广剧集
                </label>
                <div class="layui-input-block">
                    <input type="text" id="sort" disabled autocomplete="off" class="layui-input" value="" />
                </div>
            </div>

            <!-- <div class="layui-form-item" id="link_count" style="display: none;">
                <label class="layui-form-label">
                    链接数量
                </label>
                <div class="layui-input-block">
                    <input type="number" max="100" min="1" name="link_count" autocomplete="off" class="layui-input"
                        value="1" lay-verify="nums" />
                </div>
            </div> -->

            <div class="layui-form-item">
                <label class="layui-form-label">
                    <span class="x-red">*</span>投放媒体
                </label>
                <div id="pMenu" style="width:100%;flex:1"></div>
            </div>

            <div class="layui-form-item subject" style="display:none">
                <label class="layui-form-label">
                    <span class="x-red">*</span>主体
                </label>
                <div id="pSubject" style="width:100%;flex:1"></div>
            </div>
            <div class="layui-form-item asset" style="display:none">
                <label class="layui-form-label">
                    <span class="x-red">*</span>返点</label>
                <div class="layui-input-block">
                    <input type="text" id="rebate" name="rebate" autocomplete="off" class="layui-input" value=""
                        disabled />
                </div>
            </div>

            <div class="layui-form-item asset" style="display:none" id="zhanghuId">
                <label class="layui-form-label">
                    <span class="x-red">*</span>广告账户ID
                </label>

                <div class="layui-input-block">
                    <div class="fairy-tag-container">
                        <input type="text" class="fairy-tag-input advertiser_id" autocomplete="off" value="">
                    </div>
                    <div class="layui-form-mid layui-word-aux" style="color: #d70000!important">回车键确认，返回键删除</div>
                </div>
            </div>

            <div class="layui-form-item baidu" id="baidu" style="display:none">
                <label class="layui-form-label">
                    百度token
                </label>
                <div class="layui-input-block">
                    <input type="text" id="token" name="token" autocomplete="off" class="layui-input" value=""
                        placeholder='百度投放必填（回传需要用到）' />
                </div>
            </div>

            <div class="layui-form-item zch" id="'zch" >
                <label class="layui-form-label">抖音资产化</label>
                <div class="layui-input-block">
                    <input type="radio" name="is_capitalization" value="" title="否">
                    <input type="radio" name="is_capitalization" value="1" title="是" checked>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">
                    <span class="x-red">*</span>收费模板
                </label>
                <div class="layui-input-block">
                    <input type="radio" name="recharge_template_id" lay-filter="recharge_template_id" value="0"
                        title="按公共配置充值">
                    <input type="radio" name="recharge_template_id" lay-filter="recharge_template_id" value="-1"
                        title="自定义收费设置" checked>
                </div>
            </div>
            <div class="layui-form-item" id="recharge" style="display:none;">
                <label class="layui-form-label">
                    <span class="x-red">*</span>选择模板
                </label>
                <div id="pRecharge" style="width:100%;flex:1"></div>
            </div>
            <div class="layui-form-item" id="huichuan">
                <label class="layui-form-label">
                    <span class="x-red">*</span>回传开关
                </label>
                <div class="layui-input-block">
                    <input type="radio" name="is_open" value="1" title="开启" checked>
                    <input type="radio" name="is_open" value="2" title="关闭">
                </div>
            </div>
            <!-- <div class="layui-form-item" id="huichuanlv">
                <label class="layui-form-label">
                    <span class="x-red">*</span>回传率
                </label>
                <div class="layui-input-block">
                    <input type="text" name="echo_rate" autocomplete="off" class="layui-input echo_rate" value=""
                        placeholder="请输入0~100之间的整数" />
                </div>
            </div>
            <div class="layui-form-item" id="zhidhuichuan">
                <label class="layui-form-label">
                    指定金额回传<i class="layui-icon iconfont icon-lytishi1" id="tips"
                        style="margin-left:5px;font-size: 14px;"></i>
                </label>
                <div class="layui-input-block">
                    <input type="radio" name="design_switch" value="1" lay-filter="design_switch" title="开启">
                    <input type="radio" name="design_switch" value="0" lay-filter="design_switch" title="关闭" checked>
                </div>
                <div class="layui-input-block designated_amount_echo" style="display: none;"></div>
            </div> -->
            <!-- <div id="config">
                <div class="layui-form-item">
                    <label class="layui-form-label">
                        <span class="x-red">*</span>回传规则配置
                    </label>
                    <div class="layui-input-block">
                        <input type="radio" name="echo_rule_config_id" lay-filter="echo_rule_config_id" value="0"
                            title="按公共配置回传（T+7全量）">
                        <input type="radio" name="echo_rule_config_id" lay-filter="echo_rule_config_id" value="1"
                            title="按自然日配置回传">
                        <input type="radio" name="echo_rule_config_id" lay-filter="echo_rule_config_id" value="2"
                            title="仅回传首单（T+7首单）">
                    </div>
                </div>
            </div> -->

            <div class="layui-form-item">
              <label class="layui-form-label">
                 <span class="x-red">*</span>     回传模板
                </label>
                <div id="paySelect" style="width:100%;flex:1"></div>
            </div>
            <!-- <div class="layui-form-item" id="dc">
                <label class="layui-form-label">
                    <span class="x-red">*</span>低充值不回传
                </label>
                <div class="layui-input-block">
                    <input type="radio" name="is_open_low_recharge_not_echo" value="0"
                        lay-filter="is_open_low_recharge_not_echo" title="关闭" checked>
                    <input type="radio" name="is_open_low_recharge_not_echo" value="1"
                        lay-filter="is_open_low_recharge_not_echo" title="开启">
                </div>
            </div>
            <div class="layui-form-item" id="not_echo_recharge_price" style="display: none;">
                <label class="layui-form-label">
                    <span class="x-red"></span>低于此金额不回传
                    <i class="layui-icon iconfont icon-lytishi1" id="tips1"
                        style="margin-left:5px;font-size: 14px;"></i>
                </label>
                <div class="layui-input-block">
                    <input type="text" name="not_echo_recharge_price" autocomplete="off" class="layui-input" value=""
                        placeholder="小于该值的支付金额将不回传" />
                </div>
            </div>
            -->
            <div class="layui-form-item">
                <label class="layui-form-label">
                    备注
                </label>
                <div class="layui-input-block">
                    <input type="text" name="remark" value="" class="layui-input" />
                </div>
            </div>

            <input type="hidden" name="video_detail_id" id="video_detail_id" value="" />
            <input type="hidden" name="video_id" id="video_id" value="" />
            <input type="hidden" name="advertiser_id" id="advertiser_id" value="" />
            <input type="hidden" name="id" id="id" value="" />
            <input type="hidden" name="designated_amount_echo" id="designated_amount_echo"
                lay-verify="designated_amount_echo">
            <button id="submitData" class="layui-btn" lay-submit lay-filter="submitData" style="display: none;" />

        </form>
    </div>


    <script>
        let params = {
            addUrl: '/cps/link/add',
            editUrl: '/cps/link/edit',
            detailUrl: '/cps/link/detail'
        }
        form_ajax(params)
        let advertiser_id;
        let selectParams = {
            url: '/cps/link/getLaunchMedia',
            selected: [],
            tips: '选择媒体',
            name: 'media_id',
            field_id: 'id',
            field_Name: 'name',
            elem: '#pMenu',
            disabled: false
        }

        let selectParams1 = {
            url: '/cps/back/select',
            selected: [],
            tips: '选择回传配置',
            name: 'echo_rule_config_id',
            field_id: 'id',
            field_Name: 'name',
            elem: '#pBack'
        }
        let selectParams2 = {
            url: '/cps/customRechargeTemplate/select',
            selected: [],
            tips: '选择充值模板',
            name: 'recharge_template_id',
            field_id: 'id',
            field_Name: 'name',
            elem: '#pRecharge'
        }
        let getSubject = {
            url: '/cps/link/getSubject',
            selected: [],
            tips: '选择主体',
            name: 'subject_id',
            field_id: 'subject_id',
            field_Name: 'subject',
            elem: '#pSubject'
        }
        let paySelect = {
            url: '/cps/back/select',
            selected: [],
            tips: '选择模板',
            name: 'echo_rule_config_id',
            field_id: 'id',
            field_Name: 'name',
            elem: '#paySelect'
        }
        let media_id,
            subject_id;
        // 金额回传
        var designated_amount_echo,
            old_designated_amount_echo;
        let id = GetQueryString('id')
        $('#name').val(decodeURI(GetQueryString('video_name') ?? ''))
        $('#sort').val(GetQueryString('sort'))
        $('#video_detail_id').val(GetQueryString('video_detail_id'))
        $('#video_id').val(GetQueryString('video_id'))
        $('#id').val(id)

        function showRecharge() {
            $('#recharge').show()
        }

        // function infoSelectN(option,value){
        //     if(option.elem === '#pMenu'){
        //         $('#config').show()
        //         selectParams1.url = `/cps/back/select?media_id=${value}`
        //         selectN(selectParams1)
        //     }
        // }
        layui.use('form', function () {
            var form = layui.form;
            form.verify({
                nums: [
                    /^([1-9][0-9]{0,1}|100)$/, '只能输入1-100的整数'
                ],
                designated_amount_echo: function (value, item) {
                    if (value && form.val("formAjax").design_switch == 1) {
                        let designated_amount_echo = JSON.parse(value);
                        let priceList = []
                        for (let index = 0; index < designated_amount_echo.length; index++) {
                            const element = designated_amount_echo[index];
                            if (element.price == '' || element.rate == '') {
                                return '指定金额回传的金额或回传率不能为空';
                            }
                            priceList.push(element.price);
                        }
                        if (isRepeat(priceList))
                            return '指定金额回传存在金额一样的数据';



                    }

                }
            });
            if (!id) {
                form.val("formAjax", {
                    echo_rule_config_id: '0',
                    recharge_template_id: '0'
                });
            }
            // form.on('radio(echo_rule_config_id)', function (data) {
            //     if (data.value === '-1') {
            //         $('#back').show()
            //     } else {
            //         $('#back').hide()
            //     }
            //     selectParams1.selected = []
            //     selectN(selectParams1)
            // });
            form.on('radio(recharge_template_id)', function (data) {
                $('#recharge').css('display', data.value === '-1' ? 'block' : 'none')
                selectParams2.selected = []
                selectN(selectParams2)
            });
            form.on('radio(design_switch)', function (data) {
                $('.designated_amount_echo').css('display', data.value === '1' ? 'block' : 'none')
            });
            form.on('radio(is_open_low_recharge_not_echo)', function (data) {
                $('#not_echo_recharge_price').css('display', data.value === '1' ? 'block' : 'none')
            });
        });

        let video_id = GetQueryString('video_id')
        if (id) {
            Ajax(params.detailUrl, { id }).then(result => { // 链接类型
                selectParams2 = {
                    url: '/cps/customRechargeTemplate/select?video_id=' + result.data.video_id,
                    selected: [],
                    tips: '选择充值模板',
                    name: 'recharge_template_id',
                    field_id: 'id',
                    field_Name: 'name',
                    elem: '#pRecharge'
                }
                $('#link_type').attr('disabled', true)
                // 选择媒体
                selectParams.disabled = true
                selectParams.selected = [result.data.media_id]
                selectN(selectParams)
                // 主体
                getSubject.disabled = true

                // 账户
                $("#advertiser_id_input").attr('disabled', true)

                $('.advertiser_id').attr('disabled', true)
                // 选择充值模板
                selectParams2.selected = [result.data.recharge_template_id]
                selectN(selectParams2)
                // 收费设置
                paySelect.selected = [result.data?.echo_rule_config_id]
                selectN(paySelect)

                // 普通投手
                if ((is_distributor === 0 && !pid) || is_branch_office_pitcher === 1) {
                    $('.asset').show()
                    setInputTag(result.data.advertiser_id?.split(','), result.data.advertiser_id?.split(','))

                    $('.subject').show()
                    media_id = result.data.media_id
                    subject_id = result.data.subject_id
                    // 选择主体
                    getSubject.url = '/cps/link/getSubject?media_id=' + result.data.media_id
                    getSubject.selected = [result.data.subject_id]
                    selectN(getSubject)

                }
                $('#config').show()

                if (result.data.recharge_template_id) {
                    selectParams2.selected = [result.data.recharge_template_id]
                    selectN(selectParams2)
                    $('#recharge').show()
                }
                if (result.data?.designated_amount_echo) {
                    if (typeof result.data.designated_amount_echo == 'string') {
                        designated_amount_echo = JSON.parse(result.data?.designated_amount_echo)
                        old_designated_amount_echo = JSON.parse(result.data?.designated_amount_echo)
                    } else {
                        designated_amount_echo = result.data?.designated_amount_echo
                        old_designated_amount_echo = result.data?.designated_amount_echo
                    }
                } else {
                    designated_amount_echo = [{
                        price: '',
                        rate: ''
                    }]
                    old_designated_amount_echo = [{
                        price: '',
                        rate: ''
                    }]
                }
                $('.designated_amount_echo').css('display', result.data.design_switch == 1 ? 'block' : 'none')
                $('#not_echo_recharge_price').css('display', result.data.is_open_low_recharge_not_echo == 1 ? 'block' : 'none')
                setAmountEcho()
            });
        } else {
            selectParams2 = {
                url: '/cps/customRechargeTemplate/select?video_id=' + video_id,
                selected: [],
                tips: '选择充值模板',
                name: 'recharge_template_id',
                field_id: 'id',
                field_Name: 'name',
                elem: '#pRecharge'
            }
            selectN(selectParams2)
            selectN(selectParams)
            selectN(paySelect)
            designated_amount_echo = [{
                price: '',
                rate: ''
            }]
            setAmountEcho()
            // 普通投手
            if ((is_distributor === 0 && !pid) || is_branch_office_pitcher === 1) { } else {
                $('#link_count').show()
            } old_designated_amount_echo = []
        }

        function infoSelectN(option, value) {
            if (option.elem == '#pMenu') {
                // if(is_distributor === 1 || (is_distributor === 0 && pid)){
                //     return                                   
                // }
                //
                // console.log('value', value);
                if (value == 6) {
                    $('#baidu').hide()
                    $('#zhanghuId').hide()
                    // $('#zch').hide()
                    $('#huichuan').hide()
                    $('#huichuanlv').hide()
                    $('#zhidhuichuan').hide()
                    $('#config').hide()
                    $('#dc').hide()
                    $('.echo_rate').val('1')
                    $('#advertiser_id').val(Date.now())
                    $('.asset').hide()
                } else if (value == 1) {
                    // debugger                                                                                                                                                                                                                                 
                    // $('.zch').show()
                } else if (value == 3) {
                    $('#baidu').show()
                    // $('#zhanghuId').show()
                    // $('.zch').hide()
                    // $('#huichuan').show()
                    // $('#huichuanlv').show()
                    // $('#zhidhuichuan').show()
                    // $('#config').show()
                    // $('#dc').show()
                    // $('.echo_rate').val('')
                    // $('.asset').show()
                } else {
                    $('#baidu').hide()
                    $('#zhanghuId').hide()
                    // $('.zch').hide()
                    $('#huichuan').hide()
                    $('#huichuanlv').hide()
                    $('#zhidhuichuan').hide()
                    $('#config').hide()
                    $('#dc').hide()
                    $('.echo_rate').val('1')
                    $('#advertiser_id').val(Date.now())
                    $('.asset').hide()
                }
                if ((is_distributor === 1 || (is_distributor === 0 && pid && is_branch_office_manage === 0 && is_branch_office_pitcher === 0) || (is_distributor === 0 && pid && is_branch_office_manage === 1))) {
                    return;
                }
                // 修改媒体 账户ID清空
                deleteInputTag()

                // 返点清空
                $('#rebate').val('')

                media_id = value

                // 展示主体
                $('.subject').show()
                getSubject.url = '/cps/link/getSubject?media_id=' + value
                selectN(getSubject)
            }
            // 选择主体
            if (option.elem == '#pSubject') {

                option.data.forEach(item => {
                    if (item.subject_id == value) {
                        if ($('#pMenu option:selected').val() == 6) {
                            $('#advertiser_id').val(Date.now())
                            $('.asset').hide()
                        } else {
                            $('.asset').show()
                            // 展示对应的返点
                            $('#rebate').val(item.rebate)
                            deleteInputTag()
                            $('.fairy-tag-container').html('<input type="text" class="fairy-tag-input advertiser_id" autocomplete="off" value="">')
                            setInputTag([], [])
                        }
                    }
                })
            }
            // 选择充值模板
            // if (option.elem == '#pRecharge') {
            //     Ajax('/cps/recharge/detail', { id: value }).then(result => {
            //         let not_recharged_content = result.data?.not_recharged_content ? JSON.parse(result.data.not_recharged_content) : []
            //         let recharged_content = result.data?.recharged_content ? JSON.parse(result.data.recharged_content) : []
            //         let recharged_template = [
            //             ...not_recharged_content,
            //             ...recharged_content
            //         ];
            //         let recharged_price = []
            //         recharged_template.forEach(item => {
            //             recharged_price.push(item.recharge_price)
            //         })
            //         if (recharged_price.length == 0) {
            //             recharged_price = ['']
            //         }
            //         designated_amount_echo = [...new Set(recharged_price)].map(item => {
            //             return {
            //                 price: item,
            //                 rate: item ? '100' : ''
            //             }
            //         })
            //         designated_amount_echo.forEach((item, index) => {
            //             for (let ind = 0; ind < old_designated_amount_echo.length; ind++) {
            //                 const it = old_designated_amount_echo[ind];
            //                 if (Number(item.price) == Number(it.price) && Number(item.rate) == Number(it.rate)) {
            //                     designated_amount_echo[index]['update_time'] = old_designated_amount_echo[0]['update_time']
            //                     return;
            //                 } else {
            //                     designated_amount_echo[index]['update_time'] = Math.round(new Date().getTime() / 1000)
            //                 }
            //             }
            //         })
            //         setAmountEcho()
            //     });
            // }
        }

        // 广告账户ID
        function setInputTag(advertiser_id, disabledAdvertiserId) {
            deleteInputTag()
            $('#advertiser_id').val(advertiser_id.length == 0 ? '' : advertiser_id.toString())
            inputTag({
                elem: '.advertiser_id',
                data: advertiser_id,
                permanentData: disabledAdvertiserId,
                onChange: function (data, value, type) {
                    $('#advertiser_id').val(data.toString())
                }
            })
        }

        // 设置金额回传dom
        function setAmountEcho() {
            let template = '';
            designated_amount_echo.forEach((item, index) => {
                let add = `<span class="layui-badge layui-bg-blue" onclick='addAmountEcho(${index})'>
                    <i class="layui-icon layui-icon-add-1"></i>
                </span>`
                let subtract = `<span class="layui-badge layui-bg-orange" onclick='delAmountEcho(${index})'>
                    <i class="layui-icon layui-icon-subtraction"></i>
                </span>`
                template += `
                    <div class="item">
                        <div class="content">
                            <div>金额：<input type="number" autocomplete="off" class="layui-input" value="${item.price
                    }" oninput="editAmountEcho('price',${index},this)" onblur="editAmountEcho('price',${index},this)" /></div>
                            <div>回传率：<input type="number" autocomplete="off" class="layui-input" value="${item.rate
                    }" oninput="editAmountEcho('rate',${index},this)" onblur="editAmountEcho('rate',${index},this)" /></div>
                        </div>

                        <div class="operate">
                            ${index == 0 ? '' : subtract
                    }
                            ${add}
                        </div>
                    </div>
                `
            })
            $('.designated_amount_echo').html(template)
            $('#designated_amount_echo').val(JSON.stringify(designated_amount_echo))
        }
        // 添加回传金额
        function addAmountEcho() {
            designated_amount_echo.push({ price: '', rate: '' })
            setAmountEcho()
        }
        // 删除回传金额
        function delAmountEcho(index) {
            designated_amount_echo.splice(index, 1)
            setAmountEcho()
        }
        // 修改回传
        function editAmountEcho(name, index, that) {
            designated_amount_echo[index][name] = $(that).val()
            if (id) { // designated_amount_echo[index]['update_time'] = Math.round(new Date().getTime() / 1000)
                designated_amount_echo.forEach((item, index) => {
                    for (let ind = 0; ind < old_designated_amount_echo.length; ind++) {
                        const it = old_designated_amount_echo[ind];
                        if (Number(item.price) == Number(it.price) && Number(item.rate) == Number(it.rate)) {
                            designated_amount_echo[index]['update_time'] = old_designated_amount_echo[0]['update_time']
                            return;
                        } else {
                            designated_amount_echo[index]['update_time'] = Math.round(new Date().getTime() / 1000)
                        }
                    }
                })
            }
            $('#designated_amount_echo').val(JSON.stringify(designated_amount_echo))
        }

        function isRepeat(arr) {
            var hash = {};
            for (var i in arr) {
                if (hash[arr[i]])
                    return true;



                hash[arr[i]] = true;
            }
            return false;
        }

        tips('#tips', '#tips', '如开启开关优先使用指定金额回传')
        tips('#tips1', '#tips1', '低于设置的不回传充值金额将不回传')
        // 清空广告账户ID
        function deleteInputTag() {
            $("#advertiser_id").val('')
            $('.fairy-tag-container').children().each(function () {
                if ($(this).hasClass('fairy-tag')) {
                    $(this).remove()
                }
            });
        }
    </script>
</body>

</html>